import axios from "axios";
import type { AxiosInstance, AxiosRequestConfig } from "axios";
import type { DLRequestInterceptors, DLRequestConfig } from "./type";
import { ElLoading } from "element-plus";

class DLRequest {
  instance: AxiosInstance;
  interceptors: DLRequestInterceptors;
  loading: any;
  showloading?: boolean;
  constructor(config: DLRequestConfig) {
    this.instance = axios.create(config); //创建不同的实例
    this.interceptors = config.interceptors;
    this.showloading = config.showloading;
    this.instance.interceptors.request.use(
      this.interceptors.requestInterceptor,
      this.interceptors.requestInterceptorCatch
    );
    this.instance.interceptors.response.use(
      this.interceptors.responseInterceptor,
      this.interceptors.responseInterceptorCatch
    );

    //全局拦截器
    this.instance.interceptors.request.use(
      (config) => {
        if (this.showloading) {
          this.loading = ElLoading.service({
            lock: true,
            text: "正在请求数据...",
            background: "rgba(0, 0, 0, 0.5)",
          });
        }
        return config;
      },
      (err) => {
        return err;
      }
    );

    this.instance.interceptors.response.use(
      (res) => {
        if (this.showloading) {
          setTimeout(() => {
            this.loading.close(); //移除loading
          }, 100);
        }
        return res.data;
      },
      (err) => {
        this.loading.close(); //移除loadind
        return err;
      }
    );
  }
  request<T = any>(config: AxiosRequestConfig): Promise<T> {
    return new Promise((resolve, reject) => {
      this.instance.request<any, T>(config).then((res) => {
        resolve(res);
      });
    });
  }
  get<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "get" });
  }
  post<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "post" });
  }
  delete<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "delete" });
  }
  patch<T = any>(config: AxiosRequestConfig): Promise<T> {
    return this.request<T>({ ...config, method: "patch" });
  }
}
export default DLRequest;
